package com.douma.lock;

import redis.clients.jedis.Jedis;

/**
 * 抖码课堂，专注中国程序员基础内功修炼
 * 官网：douma-tech.com
 * 公众号：抖码课堂
 *
 * @作者 : 老汤
 */
public class RedisDistributeLock2 {
    private Jedis jedis;

    public RedisDistributeLock2(Jedis jedis) {
        this.jedis = jedis;
    }

    // 使用 lua 脚本保证原子性
    public boolean lock() {
        Object res = jedis.eval("local state = redis.call('GET', 'state'); " +
                "if not state or state == '0' then " +
                "redis.call('SET', 'state', '1'); " +
                "return 1 " +
                "else " +
                "return 0 " +
                "end");
        return (long)res == 1;
    }

    // 释放锁，将 state 设置为 0
    public void unlock() {
        jedis.set("state", "0");
    }
}
